//
//  PublishGoodViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/18.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "PublishGoodViewController.h"
#import "PGoodHeadCell.h"
#import "PGoodBarCell.h"
#import "PGoodDetailCell.h"
#import "ArticleTextViewCell.h"
#import "ArticleTextImgViewCell.h"
#import "ArticleModel.h"
#import "GCQiniuUploadManager.h"

@interface PublishGoodViewController () <UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) CGFloat itemWidth;

@property (strong, nonatomic) NSMutableArray *goodimgurlArray;
@property (strong, nonatomic) NSMutableArray *goodimgidArray;

@property (strong, nonatomic) NSString *docid;
@property (strong, nonatomic) UIImage *coverimg;
@property (strong, nonatomic) NSString *coverid;
@property (strong, nonatomic) NSString *coverurl;
@property (strong, nonatomic) NSMutableArray *textArray;
@property (strong, nonatomic) NSMutableArray *imgurlArray;
@property (strong, nonatomic) NSMutableArray *imgidArray;
@property (strong, nonatomic) NSMutableArray *textSortIndex;
@property (strong, nonatomic) NSMutableArray *imgSortIndex;

@end

@implementation PublishGoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.itemWidth = (ScreenWidth - 24 - 24 * 3) / 4;
    [[PublishData sharedPublishData].goodimgArray removeAllObjects];
    [[PublishData sharedPublishData].goodlocalArray removeAllObjects];
    ArticleModel *baseone = [ArticleModel new];
    baseone.type = ArticleModelTxt;
    baseone.txt = @"";
    [[PublishData sharedPublishData].goodlocalArray addObject:baseone];
    [self.tableView reloadData];
    
    [[PublishData sharedPublishData] resetPublishGoodData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"发布商品"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *button = [ViewFactory makeNavigationTextButtonWhite:@"发布"];
    [button addTarget:self action:@selector(goPublish) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightButton;
}

- (void)goPop {
    [self.view endEditing:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定要取消发布商品吗？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { //确定
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)goPublish {
    [self.view endEditing:YES];
    if ([PublishData sharedPublishData].product_title.length == 0) {
        [ViewFactory showInfoMsg:@"请输入标题！"];
        return;
    }
    
    if ([[PublishData sharedPublishData].chooseTribeID isEqualToString:@""]) {
        [ViewFactory showInfoMsg:@"请选择部落！"];
        return;
    }
    
    if ([[PublishData sharedPublishData].product_type_id isEqualToString:@""]) {
        [ViewFactory showInfoMsg:@"请选择作品分类！"];
        return;
    }
    
    if ([PublishData sharedPublishData].goodimgArray.count > 0) {
        [ViewFactory showLoading];
        [self uploadGoodImages];
    } else {
        [ViewFactory showInfoMsg:@"请至少选择一张图片!"];
        return;
    }
}

- (void)uploadGoodImages {
    [self.goodimgurlArray removeAllObjects];
    [self.goodimgidArray removeAllObjects];
    NSMutableArray *dataarray = [NSMutableArray new];
    for (NSInteger i = 0; i < [PublishData sharedPublishData].goodimgArray.count; i++) {
        UIImage *img = [PublishData sharedPublishData].goodimgArray[i];
        NSData *imgdata = UIImageJPEGRepresentation(img, HIGHSIZE);
        [dataarray addObject:imgdata];
    }
    
    [[GCQiniuUploadManager sharedInstance] uploadDatas:dataarray progress:^(float percent) {
        
    } oneTaskCompletion:^(NSError *error, NSString *link, NSInteger index) {
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
            if (index == 0 || self.coverurl == nil) {
                self.coverid = link;
                self.coverurl = resurl;
            }
            
            [self.goodimgurlArray addObject:resurl];
            [self.goodimgidArray addObject:link];
        }
    } allTasksCompletion:^{
        [self uploadImages];
    }];
}

- (void)uploadImages {
    [self.textArray removeAllObjects];
    [self.imgurlArray removeAllObjects];
    [self.imgidArray removeAllObjects];
    [self.imgSortIndex removeAllObjects];
    [self.textSortIndex removeAllObjects];
    NSMutableArray *dataarray = [NSMutableArray new];
    NSInteger startindex = 1; //startindex 0 is cover
    for (NSInteger i = 0; i < [PublishData sharedPublishData].goodlocalArray.count; i++) {
        ArticleModel *one = [PublishData sharedPublishData].goodlocalArray[i];
        if (one.type == ArticleModelImageTxt) {
            if (one.img) {
                NSData *imgdata = UIImageJPEGRepresentation(one.img, HIGHSIZE);
                [dataarray addObject:imgdata];
                [self.imgSortIndex addObject:[NSNumber numberWithInteger:startindex]];
                startindex++;
            }
            
            if (one.txt && one.txt.length > 0) {
                [self.textArray addObject:one.txt];
                [self.textSortIndex addObject:[NSNumber numberWithInteger:startindex]];
                startindex++;
            }
        } else {
            if (one.txt && one.txt.length > 0) {
                [self.textArray addObject:one.txt];
                [self.textSortIndex addObject:[NSNumber numberWithInteger:startindex]];
                startindex++;
            }
        }
    }
    
    if (dataarray.count > 0) {
        [[GCQiniuUploadManager sharedInstance] uploadDatas:dataarray progress:^(float percent) {
            
        } oneTaskCompletion:^(NSError *error, NSString *link, NSInteger index) {
            DYLog(@"upload index:%ld link:%@", index, link);
            if (link) {
                NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
                [self.imgurlArray addObject:resurl];
                [self.imgidArray addObject:link];
            }
        } allTasksCompletion:^{
            [self uploadDoc];
        }];
    } else {
        [self uploadDoc];
    }
}

- (void)uploadDoc {
//    NSString *coverid = @"";
//    if (self.imgidArray.count > 0) {
//        coverid = self.imgidArray[0];
//    }
    if (self.textSortIndex.count == 0 && self.imgSortIndex.count == 0) {
        [ViewFactory showInfoMsg:@"请填写商品详情！"];
        return;
    }
    
    NSMutableArray *parray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.textArray.count; i++) {
        NSDictionary *pdict = @{
                                @"sort_index": self.textSortIndex[i],
                                @"md": self.textArray[i]
                                };
        [parray addObject:pdict];
    }
    
    NSMutableArray *picarray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.imgidArray.count; i++) {
        NSString *imgid = self.imgidArray[i];
        NSDictionary *picdict = @{
                                  @"sort_index": self.imgSortIndex[i],
                                  @"id": imgid,
                                  @"media_type": @"00",
                                  @"tag": @[
                                          @{
                                              @"sort_index": @1,
                                              @"label_value": @"http://www.baidu.com",
                                              @"txt_orient": @"0",
                                              @"label_x": @"100",
                                              @"label_y": @"100",
                                              @"label_name": @"艺术1"
                                              },
                                          @{
                                              @"sort_index": @2,
                                              @"label_value": @"",
                                              @"txt_orient": @"0",
                                              @"label_x": @"200",
                                              @"label_y": @"200",
                                              @"label_name": @"艺术2"
                                              }
                                          ]
                                  };
        [picarray addObject:picdict];
    }
    
    NSDictionary *qndict =
    @{
      @"title": [PublishData sharedPublishData].product_title,
      @"desc": [PublishData sharedPublishData].product_title,
      @"cover_img": @{
              @"id": self.coverid,
              @"media_type": @"00",
              @"is_cover": @"00",
              @"tag": @[
                      @{
                          @"sort_index": @1,
                          @"label_value": @"http://www.baidu.com",
                          @"txt_orient": @"0",
                          @"label_x": @"100",
                          @"label_y": @"100",
                          @"label_name": @"艺术1"
                          },
                      @{
                          @"sort_index": @2,
                          @"label_value": @"",
                          @"txt_orient": @"0",
                          @"label_x": @"200",
                          @"label_y": @"200",
                          @"label_name": @"艺术2"
                          }
                      ]
              },
      @"content": @{
              @"paragraph": parray,
              @"img": picarray              }
      };
    
    NSData *qndata =[qndict JSONData];
    [[GCQiniuUploadManager sharedInstance] uploadData:qndata progress:^(float percent) {
        DYLog(@"upload percent:%f", percent);
    } completion:^(NSError *error, NSString *link, NSInteger index) {
        if (link == nil) {
            [ViewFactory showErrorStrMsg:@"上传失败！"];
            return;
        }
        
        DYLog(@"upload link:%@", link);
        NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
        self.docid = resurl;
        [self publishGood];
    }];
}

- (void)publishGood {
    //product_yunfei == -1 自定义没填
    NSString *product_title = [PublishData sharedPublishData].product_title;
    NSString *product_imgurl = @"";
    for (NSInteger i = 0; i < self.goodimgurlArray.count; i ++) {
        product_imgurl = [product_imgurl stringByAppendingString:self.goodimgurlArray[i]];
        if (i != self.goodimgurlArray.count - 1) {
            product_imgurl = [product_imgurl stringByAppendingString:@","];
        }
    }
    NSString *product_detail = self.docid;
    NSString *product_type = [PublishData sharedPublishData].product_type_id;
    NSString *product_sell_type = [PublishData sharedPublishData].product_sell_type;
    long product_yunfei = [PublishData sharedPublishData].product_yunfei;
    NSString *buluo = [PublishData sharedPublishData].chooseTribeID;
    long product_kuchun = [PublishData sharedPublishData].product_kuchun;
    double market_price = [PublishData sharedPublishData].market_price;
    NSString *chenluo = @"七天无理由退换";//[PublishData sharedPublishData].chenluo;
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/addProduct?product_title=%@&product_imgurl=%@", APIYIGOU, product_title, product_imgurl];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&product_detail=%@", product_detail]];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&product_type=%@", product_type]];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&product_sell_type=%@", product_sell_type]];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&product_yunfei=%ld", product_yunfei]];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&buluo=%@", buluo]];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&product_kuchun=%ld", product_kuchun]];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&market_price=%.2f", market_price]];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&chenluo=%@", chenluo]];
    
    if ([product_sell_type isEqualToString:@"1"]) {//拍卖
        long step_price = [PublishData sharedPublishData].step_price;
        double start_price = [PublishData sharedPublishData].start_price;
        NSString *start_tm = [PublishData sharedPublishData].start_tm;
        NSString *end_tm = [PublishData sharedPublishData].end_tm;
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&step_price=%ld", step_price]];
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&start_price=%.2f", start_price]];
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&start_tm=%@", start_tm]];
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&end_tm=%@", end_tm]];
    }
    
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [ViewFactory showSuccess:@"发布成功！"];
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"发布失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"发布失败！"];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3 + [PublishData sharedPublishData].goodlocalArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        NSInteger count = ([PublishData sharedPublishData].goodimgArray.count + 1) / 4 + (([PublishData sharedPublishData].goodimgArray.count + 1) % 4 > 0 ? 1 : 0);
        return 50 + 24 + (self.itemWidth + 19) * count;
    } else if ((indexPath.row > 0 && indexPath.row <= [PublishData sharedPublishData].goodlocalArray.count)) {
        return 120;
    } else if (indexPath.row == [PublishData sharedPublishData].goodlocalArray.count + 1) {
        return 70;
    } else if (indexPath.row == [PublishData sharedPublishData].goodlocalArray.count + 2) {
        if([DataCenter sharedDataCenter].detailType == PGoodDetailYKJ) {
            return 420;
        } else {
            return 420 + 150;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        PGoodHeadCell *cell = GET_CELL(PGoodHeadCell, @"PGoodHeadCell");
        cell.controller = self;
        return cell;
    } else if ((indexPath.row > 0 && indexPath.row <= [PublishData sharedPublishData].goodlocalArray.count)) {
        ArticleModel *localone = [[PublishData sharedPublishData].goodlocalArray objectAtIndex:indexPath.row - 1];
        if (localone.type == ArticleModelTxt) {
            ArticleTextViewCell *cell = GET_CELL(ArticleTextViewCell, @"ArticleTextViewCell");
            cell.contentTextView.text = localone.txt;
            cell.controller = self;
            cell.dataIndex = indexPath.row - 1;
            return cell;
        } else if (localone.type == ArticleModelImageTxt) {
            ArticleTextImgViewCell *cell = GET_CELL(ArticleTextImgViewCell, @"ArticleTextImgViewCell");
            cell.img.image = localone.img;
            cell.contentTextView.text = localone.txt;
            cell.controller = self;
            cell.dataIndex = indexPath.row - 1;
            cell.tagbg.hidden = YES;
            return cell;
        }
        return nil;
    } else if (indexPath.row == [PublishData sharedPublishData].goodlocalArray.count + 1) {
        PGoodBarCell *cell = GET_CELL(PGoodBarCell, @"PGoodBarCell");
        cell.controller = self;
        return cell;
    } else if (indexPath.row == [PublishData sharedPublishData].goodlocalArray.count + 2) {
        PGoodDetailCell *cell = GET_CELL(PGoodDetailCell, @"PGoodDetailCell");
        cell.controller = self;
        return cell;
    }
    return nil;
}

-(BOOL)tableView:(UITableView *) tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    //打开编辑
    return YES;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    //允许移动
    return YES;
    //return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    if (sourceIndexPath == destinationIndexPath ) return;
    
    NSInteger source = sourceIndexPath.row;
    NSInteger dest = destinationIndexPath.row;
    
    [self.tableView beginUpdates];
    ArticleModel *model = [PublishData sharedPublishData].goodlocalArray[source];
    [[PublishData sharedPublishData].goodlocalArray removeObjectAtIndex:source];
    [[PublishData sharedPublishData].goodlocalArray insertObject:model atIndex:dest];
    [self.tableView endUpdates];
    
    [tableView reloadData];
}

- (void)refreshTable {
    [self.tableView reloadData];
}

- (void)updateTable:(NSInteger)sourceIndex newIndex:(NSInteger)destIndex {
    if (sourceIndex == destIndex)
        return;
    NSIndexPath *preindex = [NSIndexPath indexPathForRow:sourceIndex inSection:0];
    NSIndexPath *nowindex = [NSIndexPath indexPathForRow:destIndex inSection:0];
    [self tableView:self.tableView moveRowAtIndexPath:preindex toIndexPath:nowindex];
}

ARRAY_INIT(goodimgidArray)
ARRAY_INIT(goodimgurlArray)
ARRAY_INIT(textArray)
ARRAY_INIT(imgurlArray)
ARRAY_INIT(imgidArray)
ARRAY_INIT(textSortIndex)
ARRAY_INIT(imgSortIndex)

@end
